<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="css/dialog.css">
    <style>
        body {
            margin: 0;
            /* background:green; */
            text-align: center;
        }

        canvas {
            margin-top: 100px;
        }

        .clickMe {
            width: 100%;
            height: 100vw;
            text-align: center;
            line-height: 100vw;
            background: red;
            font-size: 18px;
        }
    </style>
</head>

<body>
    <div class="clickMe">点击自拍或者上传头像图片</div>
    <img src="" alt="" class="testImg">
    <form action="/index.php/index/index/getFace" enctype="multipart/form-data" method="post">
        <input hidden type="file" name="pic" accept="image/*" onchange="fileDone()">
        <input hidden class="btn" type="button" value="ajax提交">
    </form>
    <button style="display: none" class="checkBtn">转为图片，base64/blob</button>
    <canvas id="myCanvas"></canvas>
    <script src="js/jquery-2.1.0.js"></script>
    <script src="js/touch-0.2.14.min.js"></script>
    <script src="js/vconsole.min.js"></script>
    <script src="js/dialog.min.js"></script>
    <script>
        var loadDialog;
        $(".clickMe").on("click", function () {
            loadDialog = $(document).dialog({
                type : 'toast',
                infoIcon: 'img/icon/loading.gif',
                infoText: '正在加载中',
                autoClose: 0
            });
            $("input[type=file]").trigger("click");
        })

        function fileDone() {
            $(".btn").trigger("click");
        }
        $(".btn").on("click", function () {
            var file = document.querySelector('[type=file]');
            // 通过FormData将文件转成二进制数据
            var formData = new FormData();
            // 将文件转二进制
            // console.log(file.files[0]);
            console.log(window.URL.createObjectURL(file.files[0]));
            var localImgPath = window.URL.createObjectURL(file.files[0]);
            //$(".testImg").attr("src",window.URL.createObjectURL(file.files[0]));
            formData.append('pic', file.files[0]);
            formData.append("winW", window.innerWidth);
            $.ajax({
                url: 'http://shuaitp.bluej.cn/index.php/index/index/getFacePos',
                type: 'POST',
                data: formData, // 上传formdata封装的数据
                dataType: 'JSON',
                cache: false, // 不缓存
                processData: false, // jQuery不要去处理发送的数据
                contentType: false, // jQuery不要去设置Content-Type请求头
                success: function (res) { //成功回调
                    console.log(res);
                    /**
                    res.res -1 未上传图片
                            0  未识别到人脸
                            1  正常识别人脸
                    */
                    if (res.res == 1) {
                        appCanvas(res.data.url, res.data.pos, 0, 0); //y轴方向矫正0.3倍的height
                    } else if (res.res == 0) {
                        // alert("未识别到人脸");
                        var facePos = {
                            left: 0,
                            top: 0,
                            width: res.data.size["0"],
                            height: res.data.size["1"],
                        }
                        appCanvas(res.data.url, facePos, 0, 0);
                    } else {
                        alert("未上传图片");
                    }
                }
            });
        })
        // window.onload = appCanvas;
        //传入图片地址和要显示到中心点的位置信息,以及矫正位置值(百分比)
        function appCanvas(imgsrc, centerPos, offsetX, offsetY) {
            var winW = window.innerWidth;
            var myCanvas = document.getElementById('myCanvas');
            myCanvas.width = winW*.7;
            myCanvas.height = winW*.7;
            var myCanW = myCanvas.width;
            var myCanH = myCanvas.height;
            //矫正位置值不传的话就为0;
            offsetX = offsetX || 0;
            offsetY = offsetY || 0;

            if (!myCanvas || !myCanvas.getContext) {
                return
            };
            // 这里开始绘制 
            var ctx = myCanvas.getContext('2d');
            drawScreen();

            var toLoadImg, ratio;

            function drawScreen() {
                ctx.save();
                toLoadImg = new Image();
                toLoadImg.onload = onImageReady;
                toLoadImg.src = imgsrc; //这里修改为本地src
            }
            //这个函数调用，一是图片加载完毕，而是鼠标拖动图片
            function onImageReady(startX, startY) {
                var imgWidth = toLoadImg.width;
                var imgHeight = toLoadImg.height;
                var firstIn = true;
                //图片加载完毕第一次进入第一个参数为事件对象e
                //鼠标拖动时传入坐标数字
                if ((typeof startX) == "number") {
                    firstIn = false;
                }
                if (firstIn) {
                    ratio = myCanW / imgWidth;
                    lastScale = ratio;

                    loadDialog.close();
                    $(".clickMe").css("display","none");
                    $(".checkBtn").css("display","inline-block");
                } else {

                }

                centerPos.width *= ratio;
                centerPos.height *= ratio;
                centerPos.top *= ratio;
                centerPos.left *= ratio;

                startX = (typeof startX) == "number" ? startX : myCanW / 2 - centerPos.left - centerPos.width / 2;
                startY = (typeof startY) == "number" ? startY : myCanH / 2 - centerPos.top - centerPos.height / 2;
                if (firstIn) { //第一次进来时要赋值lastX,lastY
                    lastX = startX;
                    lastY = startY;
                }
                ctx.save();
                ctx.clearRect(0, 0, myCanW, myCanH);

                console.log("最终应用ratio", ratio);
                console.log("最终应用startX", startX, startY);

                // ctx.drawImage(toLoadImg, startX, startY, myCanW, myCanH);
                //第四，五个参数为要绘制图像的宽高（2-5参数控制原图的裁剪大小），最后两个为要使用的图像的宽高（6-9为控制在canvas上显示图片大小）
                ctx.drawImage(toLoadImg, 0, 0, imgWidth, imgHeight, startX + centerPos.width * offsetX, startY +
                    centerPos.height * offsetY, imgWidth * ratio, imgHeight * ratio);

                var _imageData = ctx.getImageData(0, 0, myCanW, myCanH);
                var imageData = _imageData.data;
                console.log(imageData);
                var len = imageData.length / 4; //画布上像素的个数
                var cirPos = { //显示圆形的圆心,半径
                    x: myCanW / 2,
                    y: myCanH / 2,
                    r: myCanW *.3 //注意这里是半径，所以最大为0.5
                };
                for (var i = 0; i < len; i++) {
                    var x = i % myCanW; //像素点x坐标
                    var y = Math.floor(i / myCanW); //得到行数，即左边y坐标
                    var dis = Math.sqrt(Math.pow(x - cirPos.x, 2) + Math.pow(y - cirPos.y, 2));
                    if (dis >= cirPos.r) {
                        imageData[i * 4 + 3] = 60; //设置圆外透明度为60（0-255）;
                    }
                }
                ctx.putImageData(_imageData, 0, 0); //重新绘制到画布上
            }

            //下为鼠标操作
            var lastX = lastY = finX = finY = 0,
                lastScale = 1;
            touch.on(myCanvas, "drag", function (e) {
                // console.log("drag",finX,finY);
                finX = lastX + e.distanceX;
                finY = lastY + e.distanceY;
                onImageReady(finX, finY);
            })
            touch.on(myCanvas, "dragend", function (e) {
                lastX = finX;
                lastY = finY;
                console.log("drageend", lastX, lastY);
            })

            touch.on(myCanvas, "pinch", function (e) {
                console.log("pinch", e);
                ratio = lastScale * e.scale;
                console.log("ratio", ratio);
                onImageReady(finX, finY);
            })
            touch.on(myCanvas, "pinchend", function () {
                console.log("pinchend", ratio);
                lastScale = ratio;
            })

            var clickMeBtn = document.querySelector(".clickMe");
            touch.on(clickMeBtn,"rotate",function(e){
                console.log("rotate",e);
            })




            // 生成图片按钮
            $(".checkBtn").on("click",function(){
                var _imageData = ctx.getImageData(0, 0, myCanW, myCanH);
                var imageData = _imageData.data;
                var len = imageData.length / 4; //画布上像素的个数
                var cirPos = { //显示圆形的圆心,半径
                    x: myCanW / 2,
                    y: myCanH / 2,
                    r: myCanW / 4
                };
                for (var i = 0; i < len; i++) {
                    var x = i % myCanW; //像素点x坐标
                    var y = Math.floor(i / myCanW); //得到行数，即左边y坐标
                    var dis = Math.sqrt(Math.pow(x - cirPos.x, 2) + Math.pow(y - cirPos.y, 2));
                    if (dis >= cirPos.r) {
                        imageData[i * 4 + 3] = 0; //设置圆外透明度为60（0-255）;
                    }
                }
                ctx.putImageData(_imageData, 0, 0); //重新绘制到画布上
                var finalImg = myCanvas.toDataURL("image/png");
                console.log(finalImg);
                myCanvas.toBlob(function(blob){
                    console.log("方法二生成图片",blob);
                })

                $(".testImg").attr("src",finalImg);
                $("#myCanvas").css("display","none");
            })

        }
    </script>
</body>

</html>